package com.company.controller;

import com.company.mapper.EmployeeMapper;
import com.company.model.Employee;
import com.company.model.EmployeeQuery;
import com.company.util.MyBatisUtil;
import com.company.vo.PageResult;
import org.apache.ibatis.session.SqlSession;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

@WebServlet("/employee/list")
public class EmployeeListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1. 获取查询参数
        EmployeeQuery query = new EmployeeQuery();
        query.setName(request.getParameter("name"));
        query.setDepartment(request.getParameter("department"));
        query.setPosition(request.getParameter("position"));

        // 处理薪资参数（非必填）
        String minSalaryStr = request.getParameter("minSalary");
        if (minSalaryStr != null && !minSalaryStr.isEmpty()) {
            query.setMinSalary(new BigDecimal(minSalaryStr));
        }
        String maxSalaryStr = request.getParameter("maxSalary");
        if (maxSalaryStr != null && !maxSalaryStr.isEmpty()) {
            query.setMaxSalary(new BigDecimal(maxSalaryStr));
        }

        // 处理分页参数
        String pageNumStr = request.getParameter("pageNum");
        if (pageNumStr != null && !pageNumStr.isEmpty()) {
            query.setPageNum(Integer.parseInt(pageNumStr));
        }

        // 2. 调用MyBatis查询
        SqlSession session = MyBatisUtil.getSqlSession();
        EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
        List<Employee> employees = employeeMapper.getEmployeeByPage(query);
        int totalCount = employeeMapper.getTotalCount(query);
        MyBatisUtil.closeSqlSession(session);

        // 3. 封装分页结果
        PageResult<Employee> pageResult = new PageResult<>(
                employees, totalCount, query.getPageNum(), query.getPageSize()
        );

        // 4. 传递数据到页面
        request.setAttribute("pageResult", pageResult);
        request.setAttribute("query", query); // 回显查询条件
        request.setAttribute("message", request.getParameter("message"));
        request.setAttribute("error", request.getParameter("error"));
        request.getRequestDispatcher("/WEB-INF/jsp/employee/list.jsp").forward(request, response);
    }
}